package com.tedu.springboot2206.controller;

import com.tedu.springboot2206.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

@Controller
public class UserController {
    //表示保存所有用户信息的目录users
    private static File userDir;

    static {//静态块，启动一次
        userDir = new File("./users");
        if (!userDir.exists()){  //如果目录不存在
            userDir.mkdirs(); //创建目录
        }
    }

    /** 注册操作 */
    @RequestMapping("/regUser")
    public void reg(HttpServletRequest request, HttpServletResponse response){//request请求对象；response响应对象
        System.out.println("开始处理注册");
        //1)获取注册页面上的表单信息
        String username = request.getParameter("username");//获取用户名
        String password = request.getParameter("password");
        String nickname = request.getParameter("nickname");
        String ageStr = request.getParameter("age");
        System.out.println(username+","+password+","+nickname+","+ageStr);

        if (username==null||username.isEmpty()||password==null||password.isEmpty()||
            nickname==null||nickname.trim().isEmpty()||ageStr==null||ageStr.isEmpty()||
            !ageStr.matches("[0-9]+")){
            try {
                response.sendRedirect("/reg_info_error.html");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return;
        }


        //2)将该注册用户信息以User对象形式表示并序列化到文件中保存
        //将来所有的保存用户信息的文件都统一放在users目录下，并且每个保存用户的文件的名字格式:用户名.obj
        int age = Integer.parseInt(ageStr); //将年龄转为int值
        User user = new User(username,password,nickname,age);
         //         new File(userDir,username+".obj");
        File file = new File(userDir,username+".obj");
        //如果该文件存在则说明这是一个重复的用户
        if (file.exists()){
            try {
                response.sendRedirect("/have_user.html");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return;
        }
        //()自动关闭。。。看之前demo
        try (FileOutputStream fos = new FileOutputStream(file);
             ObjectOutputStream oos = new ObjectOutputStream(fos);
        ){
            oos.writeObject(user);
        } catch (IOException e) {
            e.printStackTrace();
        }

        //3)
        try {
            response.sendRedirect("/reg_success.html");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /** 登录操作 */
    @RequestMapping("/loginUser")
    public void login(HttpServletRequest request,HttpServletResponse response){
        System.out.println("开始处理登录操作。。");
        //1
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        if (username==null||username.isEmpty()||password==null||password.isEmpty()){
            try {
                response.sendRedirect("/login_info_error.html");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return;
        }
        //2
        File file = new File(userDir,username+".obj");//根据登录用户的用户名去users目录下寻找该用户信息
        if(file.exists()){//文件存在则说明该用户存在(用户名输入正确)
            //反序列化文件中该用户曾经的注册信息
            try (
                    FileInputStream fis = new FileInputStream(file);
                    ObjectInputStream ois = new ObjectInputStream(fis);
              ){
                User user = (User)ois.readObject();
                //比较登录密码和注册时输入的密码是否一致
                // a = "abc123"    b = "AbC123"
                //a.equals(b) ==> false
                //a.equalsIgnoreCase(b) ==> true
                if(user.getPassword().equals(password)){
                    //登录成功
                    response.sendRedirect("/login_success.html");
                    return;
                }
            }catch (IOException | ClassNotFoundException e){
                e.printStackTrace();
            }
        }
        //登录失败
        try {
            response.sendRedirect("/login_fail.html");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /** 用户列表 */
    @RequestMapping("/userList")
    public void userList(HttpServletRequest request,HttpServletResponse response){
        System.out.println("开始处理动态页面........");
        //1.
        List<User> userList = new ArrayList<>();
        File[] subs = userDir.listFiles(f->f.getName().endsWith(".obj"));
        for (File file : subs){
            try (FileInputStream fis = new FileInputStream(file);
                 ObjectInputStream ois = new ObjectInputStream(fis);
            ){
               User user = (User) ois.readObject();
               userList.add(user);
            } catch (IOException | ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
        System.out.println(userList);
        //2.
        try {
            response.setContentType("text/html;charset=utf-8");
            PrintWriter pw = response.getWriter();
            pw.println("<!DOCTYPE html>");
            pw.println("<html lang=\"en\">");
            pw.println("<head>");
            pw.println("<meta charset=\"UTF-8\">");
            pw.println("<title>用户列表</title>");
            pw.println("</head>");
            pw.println("<body>");
            pw.println("<center>");
            pw.println("<h1>用户列表</h1>");
            pw.println("<table border=\"1\">");
            pw.println("<tr>");
            pw.println("<td>用户名</td>");
            pw.println("<td>密码</td>");
            pw.println("<td>昵称</td>");
            pw.println("<td>年龄</td>");
            pw.println("<td>操作</td>");
            pw.println("</tr>");

            for(User user : userList) {
                pw.println("<tr>");
                pw.println("<td>"+user.getUsername()+"</td>");
                pw.println("<td>"+user.getPassword()+"</td>");
                pw.println("<td>"+user.getNickname()+"</td>");
                pw.println("<td>"+user.getAge()+"</td>");
                /*
                    http://localhost:8080/deleteUser?username=fancq
                    "<td><a href='/deleteUser?username='>删除</a></td>"
                    "<td><a href='/deleteUser?username=" + str + "'>删除</a></td>"
                    <td><a href='/deleteUser?username=fancq'>删除</a></td>
                 */
                pw.println("<td><a href='/deleteUser?username="+ user.getUsername() +"'>删除</a></td>");
                pw.println("</tr>");
            }
            pw.println("</table>");
            pw.println("</center>");
            pw.println("</body>");
            pw.println("</html>");

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /** 删除用户 */
    @RequestMapping("/deleteUser")
    public void delete(HttpServletRequest request,HttpServletResponse response){
        System.out.println("开始处理删除用户!!!!!!!!!!!!!!!!!!!!!!!");
        //http://localhost:8080/deleteUser?username=fancq
        String username = request.getParameter("username");
        System.out.println("要删除的用户是:"+username);
        File file = new File(userDir,username+".obj");
        file.delete();
        try {
            response.sendRedirect("/userList");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
